import { Component, OnInit } from '@angular/core';
import { Carousel } from '../../model/carousel';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Router, ActivatedRoute } from '@angular/router';
import { CarouselService } from '../../service/carousel.service';
import { ConfigService } from '../../service/config.service';

@Component({
  selector: 'app-editcarousel',
  templateUrl: './editcarousel.component.html',
  styleUrls: ['./editcarousel.component.css']
})
export class EditcarouselComponent implements OnInit {

  carousel:Carousel;
  parm:string;
  selectedFile:string;
  constructor(
    private http:HttpClient,
    private router:Router,
    private routerinfo:ActivatedRoute,
    private carouselservice:CarouselService,
    private configservice:ConfigService
  ) {
    this.carousel=new Carousel();
    this.parm=this.routerinfo.snapshot.params['id'];
   }

  ngOnInit() {
    if(this.parm!='add'){
      this.getCarousel(this.parm);
    }
  }

  getCarousel(id:string){
    this.carouselservice.getCarousel(id)
    .then((data:any)=>{
      if(data){
        this.carousel=data;
      }
      else{
        alert("修改异常，请刷新后重试！");
      }
      
    })

  }

  save(){
    this.carouselservice.addCarousel(this.carousel)
    .then((flag:boolean)=>{
      if(flag==true){
        this.goBack();
      }
      else{
        alert('失败');
      }
    })
  
  }

  goBack(){
    this.router.navigate(['uploadfile']);
  }

  onFileChanged(event) {
    this.selectedFile = event.target.files[0];
  }

  onUpload() {
    const uploadData = new FormData();
  uploadData.append('file', this.selectedFile);
   
  this.http.post(this.configservice.host+'/manage/uploadFile',uploadData).subscribe(
    (data:any)=>{
      //alert(data);
      //console.log(JSON.stringify(data));
      //  let host="https://localhost/public/";
      //  this.carousel.pic=host+data.pic;
      this.carousel.pic=data.pic;

    },(err:HttpErrorResponse)=>{
      console.log(err.message);
    }
  )

  }

}
